<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-10-09
 * Time: 9:17
 */
namespace app\api\controller;

use app\api\model\GetBank;
use app\api\model\Login;
use think\Db;
use think\Request;
use think\Validate;

class Index
{
//    public function ces(){
//        return urlencode('你好啊');
//    }
    /***
     * 处理前台用户注册
     * @param Request $request
     * @return string|\think\response\Json
     */
    public function appreg(Request $request)
    {
        $code = $request->param('code',null);
        if($code){
//            获取微信用户登录信息
            return "111";
        }else{
            $data = $request->param();
            $yanzheng = val($data,[
                'user'  => 'require|max:25|chsAlpha',
                'pwd'=>'require|confirm',
                'repwd'=>'require|confirm:pwd',
                'email' => 'email',
                'phone' => 'mobile',
            ]);
            if(!$yanzheng["code"]){
                return json(["code"=>401,'msg'=>$yanzheng['msg']]);
            }
            $data["pwd"] = md5(md5($data["pwd"]));
            $data["token"] = md5(time());
            $data["create_time"] = time();
            if(Db::name("user")->insert($data)){
                return json(["code"=>200,"msg"=>"注册成功"]);
            }else{
                return json(["code"=>401,"msg"=>"发生未知错误，请稍后再试"]);
            }
        }
    }

    /***
     * 处理App端前台用户登录
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Applogin(Request $request)
    {
        $data = $request->param();
        $yanzheng = val($data,[
            'user'  => 'require',
            'pwd'=>'require',
        ]);
        if(!$yanzheng){
            return json(["code"=>401,"msg"=>$yanzheng["msg"]]);
        }
        $user = Db::name("user")->where("user",$data["user"])->find();
        if($user&&$user["pwd"]==md5(md5($data["pwd"]))){
            $token  = uniqid().$user["user"];
            if(Db::name("user")->where("id",$user["id"])->update(["token"=>$token])){
                $user["token"] = $token;
                return json(["code"=>200,"msg"=>"登录成功","user"=>$user]);
            }else{
                return json(["code"=>401,"msg"=>"状态码生成失败，请重试"]);
            }
        }else{
            return json(["code"=>401,"msg"=>"账号或密码有误，请重试"]);
        }
    }

    /***
     * 排行榜
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Rankings(Request $request)
    {
        $user = Login::index($request->param("token",null));
        if(!$user){
        //未登录。返回登录页面
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        $type = $request->param("type",null);
        if($type){
            $user_list = Db::name("user")->order("$type desc,id")->select();
        }else{
            $user_list = Db::name("user")->order("grade desc,experience desc")->select();
        }
        //用户自身名次
        $current_user = \app\api\model\Index::paih($user,$user_list);

        return json(["user"=>$user,"user_list"=>$user_list,"current_user"=>$current_user]);
    }

    /***
     * 题库（还有改动）
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function yijibank(Request $request)
    {

        $class = Db::name("classes")->select();
        foreach ($class as $key=>$val){
            $val["branch"] = Db::name("branch")->where("tables_class",$val["id"])->select();
            foreach ($val["branch"] as $k=>$v){
                $val["branch"]["three_level"] = Db::name("three_level")->where("branchid",$v["id"])->select();
            }
            $bran_list[] = $val;
        }
        echo "<pre/>";
        print_r($bran_list);
//        return json(["bran_list"=>$bran_list]);
    }

    /***
     * 获取题目(点击开始考试需要传递参数，点击下一题获取当前题的基本信息通过前台获取)
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBank(Request $request){
        $token = $request->param('token',null);
        $kaoshishijian = \app\api\model\Index::sys("kaoshishijian");
        $bujishijian = \app\api\model\Index::sys("bujishijiandemoshiid");
        $user = Login::index($token);
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        if(!$user["answer_number"]){
            $zt = \app\api\model\Index::kszg($user);
            if($zt["code"]==401){
                return json(["code"=>$zt["code"],"msg"=>$zt["msg"]]);
            }
        }
        $type = $request->param('type',null);
        $difficulty = $request->param('difficulty',null);
        $status  = $request->param('status',1);

        $three_level_id = $request->param('three_level_id',null);
        //如果没有传递题目类型，判断是否属于继续考试行为
        if(!$three_level_id){
            //如果答过题没有被清空说明之前没有提交试卷，获取随便一条做过题的类型，拼装条件
            if(count($user['answer_number'])){
                $ti_id = end($user["answer_number"]);
                $timu = Db::name("bank")->where("id",$ti_id)->find();
                $three_level_id = $timu["three_level_id"];
                $type = $timu["type"];
                $difficulty = $timu["difficulty"];
            }else{
                return json(['code'=>401,'msg'=>'请输入要查的题的类型']);
            }
        }
        $data = GetBank::get($three_level_id,$type,$difficulty,$status,$user['answer_number']);
        if(!$data){
            return json(["code"=>401,"msg"=>"发生未知错误，请稍后再试"]);
        }
        $num = Db::name("user")->where("id",$user["id"])->find()["answer_number"];
        $data["tishu"] = count(json_decode($num));
        if(!$user["answer_number"]){
            if((int)$type!=(int)$bujishijian){
                return json(["code"=>200,"data"=>$data,"time"=>$kaoshishijian]);
            }
            return json(["code"=>200,"data"=>$data]);
        }else{
            if((int)$type!=(int)$bujishijian){
                $kaoshishijian = Db::name("user")->where("id",$user["id"])->find()["end_time"];
                return json(["code"=>200,"data"=>$data,"time"=>$kaoshishijian]);
            }
            return json(["code"=>200,"data"=>$data]);
        }
    }

    /***处理答题逻辑
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function ifgetBank(Request $request)
    {
        $token = $request->param('token',null);
        $end_time = $request->param("end_time",null);
        $id = $request->param("id",null);
        $right_key = $request->param("right_key",null);
        if(!$id){
            return json(["code"=>401,"msg"=>"缺少必要参数"]);
        }
        if(!$right_key){
            return json(["code"=>401,"msg"=>"请至少选择一个选项"]);
        }
        $user = Login::index($token);
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        $ti = Db::name("bank")
            ->where("id",$id)
            ->find();
        $jg = \app\api\model\Index::timu($ti,$user,$right_key,$end_time);
        return json(["code"=>$jg["code"],"msg"=>$jg["msg"]]);
    }

    /***
     * 考试结算
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Settlement(Request $request)
    {
        $token = $request->param("token");
        $user = Login::index($token);
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        $tishu = \app\api\model\Index::sys("shiti")["system_value"];
        //错题
        $data["cuoti"] = (int)$tishu - (int)$user["correct"];
        $shijian = \app\api\model\Index::sys("kaoshishijian")["system_value"];
        //用时
        $data["yongshi"] = (int)$shijian - (int)$user["end_time"];
        //百分比
        $data["baifenbi"] = ((int)$user["correct"]/(int)$tishu*100)."%";
        $jigexian = \app\api\model\Index::sys("pass")["system_value"];
        $Ksjiesuan = \app\api\model\Index::Ksjiesuan($user);
        if(!$Ksjiesuan){
            return json(["code"=>401,"msg"=>"系统错误请稍后"]);
        }

        if((int)$user["correct"]>=(int)$jigexian){
            return json(["code"=>200,"data"=>$data]);
        }else{
            return json(["code"=>201,"data"=>$data]);
        }
    }

    /***继续完成考试
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function Continueks(Request $request)
    {
        $token = $request->param("token");
        $user = Login::index($token);
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        if($user["answer_number"]){
            $ti_id = end($user["answer_number"]);
            $data["ti"] = Db::name("bank")->where("id",$ti_id)->find();
            //完成题数
            $data["num"] = count($user["answer_number"]);
            //所剩时间
            $sj = \app\api\model\Index::sys("kaoshishijian")["system_value"];
            $data["shijian"] = (int)$sj - (int)$user["end_time"];
            return json(["code"=>200,"data"=>$data]);
        }
    }

    /***补充个人资料
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function ziliao(Request $request)
    {
        $token = $request->param("token");
        $user = Login::index($token);
        if(!$user){
            return json(["code"=>401,"msg"=>"请登录"]);
        }
        $data = $request->param();
        $vili = val($data,[
            'nickname'  => 'require|max:25|chsAlpha',
            'occupation'=>'require',
            'csrq'  =>'require',
            'email' => 'email',
            'phone' => 'mobile',
        ]);
        if(!$vili){
            return json(["code"=>401,"msg"=>$vili["msg"]]);
        }
        unset($data["token"]);
        if(Db::name("user")->where("id",$user["id"])->update($data)){
            return json(["code"=>200,"msg"=>"成功"]);
        }else{
            return json(["code"=>401,"msg"=>"系统错误"]);
        }
    }

}
